package analysis;

import beans.ApacheLogEvent;
import beans.PageViewCount;
import org.apache.commons.compress.utils.Lists;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.SlidingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Date;

/**
 * @author zkq
 * @date 2022/10/2 16:02
 */
public class HotPages {
    public static void main(String[] args) throws Exception {
        // 1. 创建环境
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        // 2. 读取数据， 创建DataStream
        DataStreamSource<String> inputStream = env.readTextFile("F:\\javasecode220620\\UserBehaviorAnalysis\\NetworkFlowAnalysis\\src\\main\\resources\\apache.log");
        SingleOutputStreamOperator<ApacheLogEvent> Stream = inputStream
                .map(data -> {
                    String[] splits = data.split(" ");
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yy:HH:mm:ss");
                    Date parse = simpleDateFormat.parse(splits[3]);
                    long ts = parse.getTime();
                    return new ApacheLogEvent(splits[0], splits[1], ts, splits[5], splits[6]);
                })
                .assignTimestampsAndWatermarks(WatermarkStrategy.<ApacheLogEvent>forBoundedOutOfOrderness(Duration.ofMinutes(1))
                        .withTimestampAssigner(new SerializableTimestampAssigner<ApacheLogEvent>() {
                            @Override
                            public long extractTimestamp(ApacheLogEvent element, long recordTimestamp) {
                                return element.getTimestamp();
                            }
                        })
                );
        // 4. 分组开窗聚合，得到每个窗口内各个页面的count 值
        SingleOutputStreamOperator<PageViewCount> aggregate = Stream
                .filter(data -> "GET".equals(data.getMethod()))
                .keyBy(data -> data.getUrl())
                .window(SlidingEventTimeWindows.of(Time.minutes(10), Time.seconds(5)))
                .aggregate(new PageCountAgg(), new PageCountResult());


        // 5. 收集同一窗口的所有页面count 值，排序输出TopN
        SingleOutputStreamOperator<String> process = aggregate
                .keyBy(data -> data.getWindowEnd())
                .process(new TopNHotPage(5));

        process.print();

        env.execute("hot page job");

    }
    public static class PageCountAgg implements AggregateFunction<ApacheLogEvent,Long,Long>{

        @Override
        public Long createAccumulator() {
            return 0L;
        }

        @Override
        public Long add(ApacheLogEvent value, Long accumulator) {
            return accumulator + 1;
        }

        @Override
        public Long getResult(Long accumulator) {
            return accumulator;
        }

        @Override
        public Long merge(Long a, Long b) {
            return a + b;
        }
    }
    public static class PageCountResult extends ProcessWindowFunction<Long,PageViewCount,String, TimeWindow>{

        @Override
        public void process(String s, Context context, Iterable<Long> elements, Collector<PageViewCount> out) throws Exception {
            Long count = elements.iterator().next();
            Long windowEnd = context.window().getEnd();
            String url = s;
            out.collect(new PageViewCount(url,windowEnd,count));
        }
    }
    public static class  TopNHotPage extends KeyedProcessFunction<Long,PageViewCount,String>{
        private Integer topN;
        private ListState<PageViewCount> listState;

        public TopNHotPage(Integer topN) {
            this.topN = topN;
        }

        @Override
        public void open(Configuration parameters) throws Exception {
            listState = getRuntimeContext().getListState(new ListStateDescriptor<PageViewCount>("page-count-list", PageViewCount.class));
        }

        @Override
        public void processElement(PageViewCount value, Context ctx, Collector<String> out) throws Exception {
            listState.add(value);
            ctx.timerService().registerEventTimeTimer(value.getWindowEnd()+1);
        }

        @Override
        public void onTimer(long timestamp, OnTimerContext ctx, Collector<String> out) throws Exception {
            ArrayList<PageViewCount> list = Lists.newArrayList(listState.get().iterator());
            list.sort(new Comparator<PageViewCount>() {
                @Override
                public int compare(PageViewCount o1, PageViewCount o2) {
                    return o2.getCount().intValue() - o1.getCount().intValue();
                }
            });

            StringBuilder result = new StringBuilder();
            result.append("==================================\n");
            result.append("窗口结束时间：").append(new Timestamp(timestamp - 1L)).append("\n");

            for (int i = 0; i < Math.min(list.size(), topN); i++) {
                PageViewCount pageViewCount = list.get(i);
                result.append("No").append(i + 1).append(":")
                        .append(" 页面URL=")
                        .append(pageViewCount.getUrl())
                        .append(" 浏览量=")
                        .append(pageViewCount.getCount())
                        .append("\n");

            }
            result.append("====================================\n\n");
            Thread.sleep(5000);
            out.collect(result.toString());
        }
    }
}
